package sgd.tp2.client.net.tcp;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import sgd.tp2.api.logging.Log;
import sgd.tp2.api.net.CDRFormatType;
import sgd.tp2.client.net.Client;

public abstract class TCPClient extends Client {

	protected Socket socket = null;

	public TCPClient(CDRFormatType cdrFormatType, String serverAddress, int serverPort) {
		super(cdrFormatType, serverAddress, serverPort);
	}

	@Override
	public void run() {
		while (running) {
		}
	}

	@Override
	public void startClient() throws UnknownHostException, IOException {
		socket = new Socket(serverAddress, serverPort);
		Log.infoln("Iniciado cliente TCP:{0}:{1} a enviar o formato {2}.", serverAddress,
				serverPort, cdrFormatType);
	}

	@Override
	public void stopClient() {
		Log.insertString("\n");
		
		running = false;

		if (socket != null && !socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e) {
				Log.warningln("Nao foram fechadas as portas correctamente: {0}", e.getMessage());
			} finally {
				socket = null;
			}
		}

		Log.infoln("Servidor terminado com sucesso.");
	}
}
